<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="businessName">
              <el-input v-model="filters.businessName" clearable placeholder="商户全称"></el-input>
            </el-form-item>
            <el-form-item prop="businessShortName">
              <el-input v-model="filters.businessShortName" clearable placeholder="商户简称"></el-input>
            </el-form-item>
            <el-form-item prop="businessType">
              <el-select v-model="filters.businessType" clearable placeholder="商户类型">
                <el-option v-for="item in businessTypeList" :key="item.value" :value="item.value" :label="item.label"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="detailType">
              <el-select v-model="filters.detailType" clearable placeholder="商户详细类型">
                <el-option v-for="item in detailTypeList" :key="item.value" :value="item.value" :label="item.label"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="manageType">
              <el-select v-model="filters.manageType" clearable filterable placeholder="经营方式">
                <el-option v-for="item in manageList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="linkName">
              <el-input v-model="filters.linkName" clearable placeholder="联系人"></el-input>
            </el-form-item>
            <el-form-item prop="linkPhone">
              <el-input v-model="filters.linkPhone" clearable placeholder="联系电话"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增 </el-button>
            <el-button type="warning" plain icon="el-icon-folder" v-has="permissionExportSet" @click="handleClickExportSet()" size="mini"> 导出商户设置 </el-button>
            <el-button type="warning" plain icon="el-icon-folder" v-has="permissionExportSet" @click="handleImportBusinessSet()" size="mini"> 批量修改商户 </el-button>
            <!-- <el-upload style="display: inline-block;" action="#"
                       :on-change="handleImportBusinessSet" :show-file-list="false"
                       accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                       :auto-upload="false">
              <el-button icon="el-icon-plus" size="mini" plain type="success" v-has="permissionExportSet">导入商户设置</el-button>
            </el-upload> -->
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table
        :data="dataList"
        ref="table"
        @row-click="$refs.table.toggleRowSelection($event)"
        @selection-change="handleSelectionChange"
        :fit="true"
        highlight-current-row
        v-loading="listLoading"
        element-loading-text="数据加载中，请稍后..."
        empty-text="对不起，没有找到相关数据！"
      >
        <el-table-column type="selection" width="50" align="center"> </el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="商户Logo" width="120">
          <template slot-scope="scope">
            <!-- <div class="img-wrapper"> -->
            <el-image title="点击可预览" :src="scope.row.businessLogo" fit="cover" :preview-src-list="[scope.row.businessLogo]" :z-index="scope.$index"> </el-image>
            <!-- </div> -->
          </template>
        </el-table-column>
        <el-table-column align="center" label="商户全称" prop="businessName"> </el-table-column>
        <el-table-column align="center" label="商户简称" prop="businessShortName"> </el-table-column>

        <el-table-column align="center" label="商户类型">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatBusinessTypes(scope.row.businessType)">
                {{ formatBusinessType(scope.row.businessType) }}
              </el-tag>
            </span>
            <div>
              {{ detailTypeFilter(scope.row.detailType) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="经营方式">
          <template slot-scope="scope">
            <span>{{ scope.row.manageType == 1 ? '自运营' : '托管平台运营' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系人" prop="linkName"> </el-table-column>
        <el-table-column align="center" label="联系电话" prop="linkPhone"> </el-table-column>
        <el-table-column align="center" label="联系地址">
          <template slot-scope="scope">
            <div>
              {{ linkAddress(scope.$index) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商户状态">
          <template slot-scope="scope">
            <div>
              <el-tag size="mini" effect="dark" :type="formatBusinessStates(scope.row.businessState)">
                {{ formatBusinessState(scope.row.businessState) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column label="操作" width="136" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑 </el-dropdown-item>
                <el-dropdown-item v-has="permissionAccount" @click.native="handleClickAccount(scope.row)" v-if="scope.row.accountState">收款账户 </el-dropdown-item>
                <el-dropdown-item v-has="permissionVerifyRecord" @click.native="handleVerificationRecord(scope.row)">查看核销记录</el-dropdown-item>
                <el-dropdown-item v-has="permissionWeight" @click.native="handleWeight(scope.row)"> 设置权重 </el-dropdown-item>
                <el-dropdown-item v-has="permissionSetDiscount" @click.native="handleDiscount(scope.row)"> 设置折扣 </el-dropdown-item>
                <el-dropdown-item v-has="permissionBusinessServer" @click.native="handleBusinessServer(scope.row)">查看货品库</el-dropdown-item>
                <el-dropdown-item v-has="permissionOpenUser" v-if="scope.row.businessState == 0" @click.native="handleClickOpenUser(scope.row)">开通账号 </el-dropdown-item>
                <el-dropdown-item v-has="permissionCheckInfo" v-if="scope.row.businessState" @click.native="handleClickBusinessAccount(scope.row)">查看账号信息 </el-dropdown-item>
                <!--<el-dropdown-item v-has="permissionEditGoods" @click.native="handleClickUpdateGV(scope.row)">设置经营产品
                </el-dropdown-item>-->
                <el-dropdown-item v-has="permissionUnionWaiter" @click.native="handleAssoicateWaiter(scope.row)"> 关联公共服务员 </el-dropdown-item>
                <el-dropdown-item v-has="permissionSetAddress" v-if="scope.row.businessType == 4 || scope.row.businessType == 3" @click.native="handleSetAddress(scope.row)">设置管理范围 </el-dropdown-item>
                <el-dropdown-item v-has="permissionViewGoods" @click.native="handleClickSeeGV(scope.row)">查看经营产品 </el-dropdown-item>
                <el-dropdown-item v-has="permissionDeliveryModel" @click.native="handleSetDeliveryModel(scope.row)">设置配送费模板 </el-dropdown-item>
                <el-dropdown-item v-has="permissionUnionBusiness" @click.native="handleAssoicateBusiness(scope.row)">关联商户 </el-dropdown-item>
                <el-dropdown-item v-has="permissionUpAllGoods" @click.native="handleClickUpAllGoods(scope.row)">上架所有产品 </el-dropdown-item>
                <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除 </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
    <AssoicateBusiness :businessId="businessId" :show="showAssoicate" @closeAssociate="showAssoicate = false"> </AssoicateBusiness>

    <!-- 设置权重 -->
    <el-dialog center title="设置权重" width="400px" :visible.sync="showWeight">
      <div>
        <el-input type="number" v-model.number="weight" placeholder="请输入整数" clearable> </el-input>
        <div style="color: red">说明：权重值越大，商户排序越靠前。平均值99，权重值范围：1-999999</div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="setWeight"> 保 存 </el-button>
      </div>
    </el-dialog>

    <!-- 开通账号 -->
    <template v-if="openUser.show">
      <el-dialog center title="开通账号" width="400px" :visible.sync="openUser.yes" :before-close="closeOpenUser">
        <el-form ref="openUser" :inline="true" label-width="100px" :model="openUser" :rules="openUserRules">
          <el-row style="padding-left: 100px; color: red; font-size: 14px"> 初始密码默认为123456 </el-row>
          <el-form-item label="登录账号" prop="userName">
            <el-input v-model="openUser.userName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="绑定手机号" prop="phone">
            <el-input type="number" v-model="openUser.phone"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button type="primary" @click="confirmOpenUser">开通</el-button>
          <el-button @click="openUser.show = false">取消</el-button>
        </div>
      </el-dialog>
    </template>

    <!-- 商户账户信息 -->
    <el-dialog center :visible.sync="businessAccount.show" title="商户账户">
      <el-table :data="businessAccount.list">
        <el-table-column label="用户姓名" prop="fullName" align="center"> </el-table-column>
        <el-table-column label="登录账号" prop="userName" align="center"> </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleResetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 关联公共服务员 -->
    <el-dialog center :visible.sync="waiter.show" title="关联公共服务员" width="fit-content">
      <el-select style="width: 300px" placeholder="请选择服务员" v-model="waiter.waiterId" multiple>
        <el-option v-for="item in waiterList" :value="item.id" :label="item.name" :key="item.id"></el-option>
      </el-select>
      <div slot="footer">
        <el-button type="primary" @click="confirmAssoicateWaiter"> 确定 </el-button>
        <el-button @click="waiter.show = false"> 取消 </el-button>
      </div>
    </el-dialog>
    <!-- 设置经营范围配送费模板 -->
    <SetDeliveryModel v-model="deliveryModel.show" :list="deliveryModel.list" :modelList="deliveryModel.modelList" @confirm="confirmSetDM"></SetDeliveryModel>
    <SetAddress :show.sync="setAddress.show" :list="setAddress.list" @confirm="confirmSetAddress" :level="setAddress.level"></SetAddress>
    <!-- v-if="setAddress.show"  -->
    <VerificationRecord :show.sync="verification.show" :businessId="rowItem.businessId" :list="verification.list"></VerificationRecord>

    <!-- 批量修改商户 -->
    <el-dialog title="导入修改文件" :visible.sync="businessSet.show" width="fit-content" center :close-on-click-modal="false">
      <div style="margin: 50px 100px">
        <el-upload :class="['upload', businessSet.file ? '' : 'no-file']" action="#" :auto-upload="false" :on-change="getBusinessSetFile" accept=".xls,.xlsx" :show-file-list="false">
          <i v-if="!businessSet.file" class="el-icon-plus"></i>
          <div class="excel-file" v-else>
            <img src="/src/assets/img/excel.png" alt="" />
            <div>
              {{ businessSet.file.name }}
            </div>
          </div>
        </el-upload>
        <div style="margin-top: 4px">
          <a style="color: red; text-decoration: none" :href="businessSet.imoprtModule"> 下载导入模板 </a>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="confirmImportBusinessSet" type="primary">确定</el-button>
        <el-button @click="businessSet.show = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 一键设置折扣 -->
    <el-dialog center title="一键设置折扣" width="400px" :visible.sync="showDiscount">
      <div>
        <el-form ref="form" :model="discountInfo" label-width="80px">
          <el-form-item label="修改类型">
            <el-radio-group v-model="discountInfo.discountType">
              <el-radio :label="1">商户比例折扣</el-radio>
              <el-radio :label="2">打包比例折扣</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="比例值(%)">
            <el-input placeholder="请输入比例值" v-model="discountInfo.val" clearable> </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="operateDiscount(1)"> 保 存 </el-button>
        <el-button type="default" @click="operateDiscount(2)"> 取 消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import BusinessApi from '@/api/business/business';
import GoodsApi from '@/api/goods/goods';
import DeliveryModelApi from '../../api/business/deliveryModel';
import * as message from '@/constants/message';
import AuthApi from '@/api/system/auth';
import fileDownload from 'js-file-download';
import AssoicateBusiness from '@/components/assoicateBusiness';
import SetDeliveryModel from './components/SetDeliveryModel.vue';
import VerificationRecord from './components/VerificationRecord.vue';
import SetAddress from '@/components/SetAddress.vue';
import WaiterApi from '@/api/business/waiter';
import importExcel from '@/excel/importExcel';
import AdminVillageApi from '@/api/common/adminVillage';
import UploadOss from '../../components/UploadOss.vue';
import { BATCH_MODIFY_BUSINESS } from '@/constants/constants';
export default {
  name: 'BusinessManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      imgList: [],
      listLoading: true,
      filters: {
        businessName: '',
        businessShortName: '',
        manageType: '',
        businessType: '',
        linkName: '',
        linkPhone: '',
        detailType: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      // 商户类型列表
      businessTypeList: [
        { value: 1, label: '大众' },
        { value: 2, label: '专属' },
        // { value: 3, label: '平台' },
        { value: 4, label: '经销' },
      ],
      detailTypeList: [
        { value: 1, label: '普通' },
        { value: 2, label: '社区商家' },
        { value: 3, label: '急救商家' },
        { value: 4, label: '社区医院商家' },
        { value: 5, label: '物业商家' },
      ],
      manageList: [
        { value: 1, label: '自运营' },
        { value: 2, label: '托管平台运营' },
      ],

      permissionAdd: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_EDIT',
      permissionDelete: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_DELETE',
      permissionWeight: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_WEIGHT',
      permissionSetDiscount: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_SETDISCOUNT',
      permissionOpenUser: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_OPEN_USER',
      permissionEditGoods: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_EDIT_GOODS',
      permissionViewGoods: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_VIEW_GOODS',
      permissionUnionBusiness: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_UNION_BUSINESS',
      permissionUpAllGoods: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_UP_ALL_GOODS',
      permissionBusinessServer: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_BUSINESS_SERVER',
      permissionCheckInfo: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_CHECK_INFO',
      permissionUnionWaiter: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_UNION_WAITER',
      permissionDeliveryModel: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_DELIVERY_MODEL',
      permissionExportSet: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_EXPORT_SET',
      permissionAccount: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_ACCOUNT',
      permissionSetAddress: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_SET_ADDRESS',
      permissionVerifyRecord: 'SYSTEM_MANAGER_BUSINESS_INFO_LIST_VERIFY_RECORD',
      businessId: '',
      showAssoicate: false,
      showWeight: false,
      showDiscount: false,
      discountInfo: {
        val: '',
        discountType: 1,
      },
      weight: '',
      openUser: {
        show: false,
        userName: '',
        phone: '',
        businessId: '',
        yes: true,
      },
      waiter: {
        show: false,
        waiterId: [],
      },
      waiterList: [],
      businessAccount: {
        show: false,
        list: [],
        modelList: [],
      },
      openUserRules: {
        userName: [{ required: true, message: '请填写账号' }],
        phone: [
          {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: '电话号码格式错误',
            trigger: 'blur',
          },
        ],
      },
      deliveryModel: {
        show: false,
        // list:[]
      },
      setAddress: {
        show: false,
        list: [],
        level: 5,
      },
      // 核销记录
      verification: {
        show: false,
      },
      rowItem: {},
      businessSet: {
        show: false,
        file: '',
        imoprtModule: BATCH_MODIFY_BUSINESS,
      },
      selectForm: {
        ids: [],
      },
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  components: {
    AssoicateBusiness,
    SetDeliveryModel,
    SetAddress,
    VerificationRecord,
    UploadOss,
  },
  watch: {
    //to去哪，from从哪来
    // $route(to,from){
    //   if(from.path =='/equip/specimenEdit' || from.path=='/equip/specimenAdd'){
    //       this.listData();
    //   }
    // }
  },
  methods: {
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.listData();
      _this.getTableHeight();
      _this.getWaiterList();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    // 把省市区和详细地址合并起来为联系地址
    linkAddress(index) {
      let prevAddress = this.dataList[index].provinceName + this.dataList[index].cityName + this.dataList[index].areaName;
      let streetName = this.dataList[index].streetName ? this.dataList[index].streetName : '';
      let address = this.dataList[index].address ? this.dataList[index].address : '';
      return prevAddress + streetName + address;
    },
    formatBusinessState(cellValue) {
      if (cellValue === 0) {
        return '未开通';
      } else if (cellValue === 1) {
        return '营业';
      } else if (cellValue === 2) {
        return '打烊';
      }
    },
    formatBusinessStates(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 2) {
        return 'warning';
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatBusinessType(cellValue) {
      if (cellValue === 1) {
        return '大众';
      } else if (cellValue === 2) {
        return '专属';
      } else if (cellValue === 3) {
        return '平台';
      } else if (cellValue === 4) {
        return '经销';
      }
    },
    formatBusinessTypes(cellValue) {
      if (cellValue === 1) {
        return '';
      } else if (cellValue === 2) {
        return 'danger';
      } else if (cellValue === 3) {
        return 'success';
      } else if (cellValue === 4) {
        return 'warning';
      }
    },

    detailTypeFilter(cellValue) {
      if (cellValue === 1) {
        return '普通';
      } else if (cellValue === 2) {
        return '社区商家';
      } else if (cellValue === 3) {
        return '急救商家';
      } else if (cellValue === 4) {
        return '社区医院商家';
      } else if (cellValue === 5) {
        return '物业商家';
      }
    },
    //
    getWaiterList() {
      WaiterApi.listIdName({ waiterType: 2 }).then((res) => {
        this.waiterList = res.data;
      });
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/business/businessAdd');
    },
    handleClickExportSet() {
      if (this.selectForm.ids.length == 0) {
        this.$message.error('请先选择商户');
        return false;
      }
      const params = {
        businessIds: this.selectForm.ids.toString(),
      };
      let loading = this.$loading({
        lock: true,
        text: '导出中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      BusinessApi.exportSetInfo(params)
        .then((res) => {
          fileDownload(res, '修改商户设置表格.xlsx');
        })
        .finally(() => {
          loading.close();
        });
    },
    handleSelectionChange(value) {
      this.selectForm.ids = value.map((item) => item.businessId);
    },
    handleImportBusinessSet() {
      this.businessSet.show = true;
      this.businessSet.file = '';
      // console.log(file)
      // return
      // importExcel(file, 0, ["businessId","businessName","businessShortName",'discount','packageDiscount','percentage','startPrice','autoCompleteHours']).then(res => {
      //   res = res.map(item => ({businessId:item.businessId||"",discount:item.discount||"",packageDiscount:item.packageDiscount||"",percentage:item.percentage||"",startPrice:item.startPrice||"",autoCompleteHours:item.autoCompleteHours||""}))
      //   const params = {list:res}
      //   BusinessApi.updateImportSetInfo(params).then(res => {
      //     this.$Utils.notifySuccess()
      //   })
      // })
    },
    getBusinessSetFile(file) {
      this.businessSet.file = file;
    },
    async confirmImportBusinessSet() {
      const {
        businessSet: { file },
      } = this;
      let res = await importExcel(file, 0, ['businessId', 'businessName', 'businessShortName', 'discount', 'packageDiscount', 'percentage', 'startPrice', 'autoCompleteHours']);
      res = res.map((item) => ({
        businessId: item.businessId || '',
        discount: item.discount || '',
        packageDiscount: item.packageDiscount || '',
        percentage: item.percentage || '',
        startPrice: item.startPrice || '',
        autoCompleteHours: item.autoCompleteHours || '',
      }));
      const params = { list: res };
      res = await BusinessApi.updateImportSetInfo(params);
      this.$Utils.notifySuccess();
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/business/businessEdit',
        query: { id: row.businessId },
      });
    },
    handleClickUpdateGV(row) {
      let _this = this;
      _this.$router.push({
        path: '/business/businessVillageGoodsAdd',
        query: { id: row.businessId },
      });
    },
    handleClickSeeGV(row) {
      let _this = this;
      _this.$router.push({
        path: '/goods/goodsManagement',
        query: { businessId: row.businessId },
      });
    },
    // 设置管理范围
    async handleSetAddress(row) {
      const { setAddress } = this;
      this.rowItem = row;
      setAddress.level = row.businessType == 3 && row.detailType == 1 ? 3 : 5;
      const res = await AdminVillageApi.listVillage({
        businessId: row.businessId,
      });
      setAddress.list = res.data || [];
      setAddress.show = true;
    },
    // 确认设置管理范围
    async confirmSetAddress() {
      const {
        rowItem: { businessId },
        setAddress,
      } = this;
      const params = {
        businessId,
        list: [],
      };
      await this.$confirm('确认保存', '提示', {});
      setAddress.list.forEach((item) => {
        const obj = { ...item };
        delete obj.villageList;
        params.list.push(Object.assign(obj, { levels: obj.villageId ? 5 : obj.levels }));
      });
      setAddress.show = false;
      await AdminVillageApi.setManagementScope(params);
      this.$Utils.notifySuccess('设置成功');
    },
    async handleSetDeliveryModel(row) {
      const { businessId } = row;
      const { deliveryModel } = this;
      let res = await DeliveryModelApi.getRelationByBusiness({ businessId });
      deliveryModel.list = [];
      res = res.data || [];
      let title = '';
      for (let item in res) {
        switch (item) {
          case '1':
            title = '专属';
            break;
          case '2':
            title = '小区';
            break;
          case '3':
            title = '公里数';
            break;
          case '4':
            title = '省市区';
            break;
        }
        deliveryModel.list.push({
          title,
          list: res[item],
        });
      }
      let res2 = await DeliveryModelApi.listIdName({ businessId });
      deliveryModel.modelList = res2.data;
      deliveryModel.show = true;
    },
    confirmSetDM() {
      const { deliveryModel } = this;
      const params = {
        list: deliveryModel.list
          .flatMap((item) => item.list)
          .map((item) => ({
            businessVillageId: item.businessVillageId,
            modelId: item.modelId,
          })),
      };

      DeliveryModelApi.setRelation(params).then((res) => {
        this.$Utils.notifySuccess();
        deliveryModel.show = false;
      });
    },
    handleAssoicateBusiness(row) {
      this.showAssoicate = true;
      this.businessId = row.businessId;
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/business/businessDetail',
        query: { id: row.businessId },
      });
    },
    handleAssoicateWaiter(row) {
      const { waiter } = this;
      this.businessId = row.businessId;
      BusinessApi.listRelationData({ businessId: row.businessId }).then((res) => {
        waiter.show = true;
        waiter.waiterId = res.data.map((item) => item.id);
      });
    },
    confirmAssoicateWaiter() {
      const { waiter, businessId } = this;
      const params = {
        ids: waiter.waiterId,
        id: businessId,
      };
      BusinessApi.batchSetRelation(params).then(() => {
        waiter.show = false;
        this.$Utils.notifySuccess('关联成功');
      });
    },
    handleClickOpenUser(row) {
      const { openUser } = this;
      openUser.businessId = row.businessId;
      openUser.userName = row.businessName;
      openUser.phone = '';
      openUser.show = true;
    },
    confirmOpenUser() {
      const { openUser } = this;
      this.$refs.openUser.validate((res) => {
        console.log(res);
        if (res) {
          this.$confirm('是否开通商户账号？', message.TITLE_PROMPT, {}).then(() => {
            const params = {
              userName: openUser.userName,
              businessId: openUser.businessId,
              phone: openUser.phone,
            };
            BusinessApi.openBusiness(params).then((res) => {
              openUser.show = false;
              this.listData();
              this.$Utils.notifySuccess('开通成功');
            });
          });
        }
      });
    },
    closeOpenUser() {
      this.openUser.show = false;
    },
    handleClickBusinessAccount(row) {
      BusinessApi.getBusinessAccount({ businessId: row.businessId }).then((res) => {
        this.businessAccount.show = true;
        this.businessAccount.list = res.data || [];
      });
    },
    handleClickUpAllGoods(row) {
      this.$confirm('是否上架该商户所有产品？', message.TITLE_PROMPT, {}).then(() => {
        GoodsApi.startUsingGoods({ businessId: row.businessId }).then((res) => {
          this.listData();
          this.$Utils.notifySuccess();
        });
      });
    },
    handleResetPassword(row) {
      this.$confirm('是否重置密码', message.TITLE_PROMPT, {}).then(() => {
        AuthApi.resetUserPwd({ userId: row.userId }).then((res) => {
          this.$Utils.notifySuccess('重置密码成功');
          // this.listData()
        });
      });
    },
    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        BusinessApi.deleteBusiness({
          id: row.businessId,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        BusinessApi.deleteBusiness({
          id: val.businessId,
          state: -1,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickAccount(row) {
      this.$router.push({
        path: '/business/businessAccount',
        query: {
          id: row.businessId,
        },
      });
    },
    // 查看核销记录
    async handleVerificationRecord(row) {
      const { verification } = this;
      this.rowItem = row;
      verification.show = true;
    },
    handleWeight(row) {
      this.showWeight = true;
      this.businessId = row.businessId;
      let params = {
        businessId: row.businessId,
      };
      BusinessApi.getBusinessWeight(params).then((res) => {
        this.weight = res.data;
      });
    },
    handleDiscount(row) {
      this.showDiscount = true;
      this.businessId = row.businessId;
    },
    operateDiscount(i) {
      //1 提交 2 取消
      if (i == 1) {
        if (!this.discountInfo.val) {
          this.$message({
            type: 'error',
            message: '请输入比例值',
          });
          return;
        }
        let loading = this.$loading({
          lock: true,
          text: '设置中...',
          // background: "rgba(0, 0, 0, 0.7)",
        });
        let data = {
          businessId: this.businessId,
          type: this.discountInfo.discountType,
        };
        this.discountInfo.discountType == 1 ? (data.discount = this.discountInfo.val) : (data.packageDiscount = this.discountInfo.val);
        BusinessApi.setDiscount(data)
          .then((res) => {
            loading.close();
            if (res.status == 0) {
              this.$Utils.notifySuccess('设置成功!');
              this.operateDiscount(2);
              this.listLoading = true;
              this.listData();
            }
          })
          .catch((err) => {
            loading.close();
          });
      } else {
        this.showDiscount = false;
        this.discountInfo = {
          val: '',
          discountType: 1,
        };
      }
    },
    setWeight() {
      if (this.weight || this.weight === 0) {
        this.$confirm('确定保存吗?', '提示', {}).then((res) => {
          let params = {
            businessId: this.businessId,
            weight: this.weight,
          };
          BusinessApi.setBusinessWeight(params).then((res) => {
            this.showWeight = false;
            this.$Utils.notifySuccess('设置成功!');
          });
        });
      } else {
        this.$message({
          type: 'error',
          message: '请输入权重',
        });
      }
    },
    handleBusinessServer(row) {
      this.$router.push({
        path: '/goods/businessServerManagement',
        query: {
          businessId: row.businessId,
        },
      });
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      // 获取列表数据
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      cond.linkName = _this.filters.linkName;
      cond.linkPhone = _this.filters.linkPhone;
      cond.businessType = _this.filters.businessType;
      cond.businessName = _this.filters.businessName;
      cond.businessShortName = _this.filters.businessShortName;
      cond.manageType = _this.filters.manageType;
      cond.detailType = _this.filters.detailType;
      BusinessApi.listBusiness(cond)
        .then((res) => {
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.listLoading = false;
          _this.$refs.table.bodyWrapper.scrollTop = 0;
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
.upload {
  .el-icon-plus {
    font-size: 30px;
  }
  .excel-file {
    height: 100px;
    text-align: center;
    img {
      width: 100px;
    }
  }
}
.no-file {
  &::v-deep .el-upload {
    height: 150px;
    width: 150px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    border: 1px rgb(160, 160, 160) dashed;
    border-radius: 4px;
    &:hover {
      border-color: black;
    }
  }
}
</style>
